<!--
 * @Description:
 * @Author: FangYaoTang
 * @Date: 2023-08-16 09:20:58
 * @LastEditor: FangYaoTang
 * @LastEditTime: 2023-09-12 14:33:45
 * @Copyright: by 南阳剧有钱网络科技有限公司 禁止任何形式（包含二次开发）转售系统源码，违者必究。
-->

<template>
	<view class="VideoPay" :class="{ active: show }" @click="$emit('close')">
		<view class="popup" @click.stop="">
			<view class="p_head">
				<view class="left">
					<!-- <text class="text1">支持作者创作，解锁后继续阅读</text> -->
				</view>
				<view class="right" :style="'color:' + isColor" @click="$emit('close')">{{$t('a257')}}</view>
			</view>
			<view class="p_text">
				<view class="left">
					<text class="text1">{{$t('a259')}}：</text>
					<text class="text2" :style="'color:' + isColor">{{ $str($t('a260'), price) }}</text>
				</view>
				<view class="right">{{$str($t('a261'), userInfoStore.score || 0 )}}</view>
			</view>
			<view class="p_list">
				<view class="item" v-for="(item, index) in integralData" :key="index"
					@click="recharge('integral', item.id, item.amount, item.productId)">
					<view class="content">
						<view class="line1">
							<text class="text1">{{ item.amount }}</text>
							<text class="text2">元</text>
						</view>
						<view class="line2">
							<!-- <text class="text1">{{ item.original_usable }}</text> -->
							<text class="text2" v-if="item.info">{{ item.info }}</text>
							<!-- <text class="text2">积分</text> -->
						</view>
					</view>
					<view class="badge" v-if="item.flag">{{ item.flag }}</view>
				</view>
				<view class="item" v-for="(item, index) in vipData" :key="index"
					@click="recharge('member', item.id, item.amount, item.productId)">
					<view class="content">
						<view class="line1">
							<text class="text1">{{ item.amount }}/{{ item.info }}</text>
						</view>
						<view class="line2">
							<text class="text2">{{ $t('a263') }}</text>
						</view>
					</view>
					<view class="tips">{{$t('a264')}}</view>
				</view>
				<!-- <view class="item item2"  @click="gotoPage('/pages/user/integral/task')">
					<view class="content">
						<view class="line1">
							<text class="text1">免费积分</text>
						</view>
						<view class="line2">
							<text class="text1">做任务获取积分</text>
						</view>
					</view>
				</view> -->
				<!-- #ifdef MP-WEIXIN -->
				<!-- <view class="item item2"  v-if="token && ad" @click="$emit('showAd'), $emit('close')">
					<view class="content">
						<view class="line1">
							<text class="text1">每日任务</text>
						</view>
						<view class="line2">
							<text class="text1">看视频获取积分</text>
						</view>
					</view>
				</view> -->
				<!-- #endif -->
				<!-- <view class="item item2" @click="jumpView('/pages/user/info/contact')">
					<view class="content">
						<view class="line1">
							<text class="text1">联系我们</text>
						</view>
					</view>
				</view> -->
			</view>
			<view class="p_info">{{ $t('a265') }}</view>
		</view>
	</view>
</template>

<script>
	import { getInfo } from '../../../utils/index'
	import {
		productList,
		productListJf
	} from '../api'
	
	// import { ApplePay } from '../../../utils/applePay.js'
	
	export default {
		name: 'VideoPay',
		props: {
			show: {
				type: Boolean,
				default: false
			},
			price: {
				type: Number,
				default: 0
			},
			ad: {
				type: Boolean,
				default: false
			},
			userInfoStore: {
				type: Object,
				default: () => {}
			}
		},
		data() {
			return {
				// userInfoStore: this.$store.state.user.userInfo,
				integralData: [],
				vipData: [],
				buttonLoading: true,
				isAdLoading: false,
				isColor: 'white',
				applePay: null,
			}
		},
		// computed: {
		//   ...mapGetters('user', ['token', 'userInfo']),
		//   ...mapGetters('app', ['iosIsPay', 'config'])
		// },
		watch: {
			userInfo: {
				deep: true,
				handler: function(newValue, oldValue) {
					this.userInfoStore = newValue
				}
			},
			show(newValue, oldValue) {
				if (newValue) {
					this.token && this.getUserInfo()
				}
			}
		},
		created() {
			this.isColor = 'white'
			this.getIntegralList()
			this.getVipList()
		},
		onShow() {
			this.buttonLoading = true
		},
		methods: {
			// ...mapActions('user', ['getUserInfo']),
			gotoPage(url) {
				if (!this.token) return this.$u.toast(this.$t('video2'))
				// #ifdef MP-WEIXIN
				if (!this.iosIsPay) return this.jumpView('/pages/user/info/contact')
				// #endif
				this.jumpView(url)
			},
			// 获取积分套餐列表
			getIntegralList() {
				productListJf().then(res => {
					res.data && res.data.length && (this.integralData = res.data)
				})
			},
			// 获取vip套装列表
			getVipList() {
				productList().then(res => {
					res.data && res.data && (this.vipData = res.data)
				})
			},
			// 充值
			recharge(type, id, price, productId) {
				if (!getInfo('VideoToken')) return uni.showToast({
					title: this.$t('video2'),
					icon: 'none'
				})

				// #ifdef MP-WEIXIN
				if (!this.iosIsPay) return this.jumpView('/pages/user/info/contact')
				// #endif

				// if(this.buttonLoading) {
				// 	this.buttonLoading = false
				// uni.showLoading({
				//   title: '开通中...',
				//   mask: true
				// })
				// console.log('webUni',webUni.postMessage)
				// console.log();
				
				// this.applePay.pay([productId], null, null, () => {})
				
				webUni.postMessage({
					data: {
						id,
						type,
						pay_amount: price,
						productId,
						navType: 'navigateTo',
						url: `/pages/shouyitai/index?id=${id}&type=${type}&pay_amount=${price}&productId=${productId}`
					}
				})
				// document.addEventListener('UniAppJSBridgeReady', function () {
				// webUni.navigateTo({ url: `/pages/shouyitai/index?id=${id}&type=${type}&pay_amount=${price}` })
				// })
				// window.location.href =  `/pages/shouyitai/index?id=${id}&type=${type}&pay_amount=${price}`
				// uni.navigateTo({ url: `/pages/shouyitai/index?id=${id}&type=${type}&pay_amount=${price}` })
				
				uni.$emit('updateUserInfo', true)
				uni.$emit('close')
				return
				if (type === 'integral') {
					this.$request('integral.create', {
							usable_id: id,
							total_fee: price,
							platform: this.$utils.platforms()
						})
						.then(res => {
							if (res.code === 1) {
								this.callPay(res.data.order_sn, 'wechat', res.data.platform)
							} else {
								this.buttonLoading = true
							}
						})
						.catch(err => {
							this.buttonLoading = true
						})
				} else if (type === 'member') {
					uni.navigateTo({ url: `/pages/shouyitai/index?id=${id}&type=${type}&pay_amount=${price}` })
					// this.$request('order.create', {
					// 	vip_id: id,
					// 	total_fee: price,
					// 	platform: this.$utils.platforms()
					// }).then(res => {
					// 	if(res.code === 1) {
					// 		this.callPay(res.data.order_sn, 'wechat', res.data.platform)
					// 	} else {
					// 		this.buttonLoading = true
					// 	}
					// }).catch(err => {
					// 	this.buttonLoading = true
					// })
				}
				// }
			},
			// 获取支付参数
			callPay(order_sn, payment, platform) {
				this.$request('common.ifxunipay').then(res => {
					console.log(res)
					if (res.data.xunipay_switch == 0) {
						this.$request('common.pay', {
							order_sn,
							payment,
							platform
						}).then(res => {
							console.log(res)
							if (res.code === 1) {
								if (platform == 'H5') {
									const div = document.createElement('divpay')
									div.innerHTML = res.data.pay_data
									document.body.appendChild(div)
								} else {
									this.pay(res.data.pay_data)
								}
							}
						})
					} else {
						// #ifdef MP-WEIXIN
						uni.login({
							provider: 'weixin',
							success: success => {
								if (success.errMsg === 'login:ok') {
									this.$request('common.xunipay', {
										order_sn,
										payment,
										platform,
										code: success.code
									}).then(res => {
										console.log(res)
										if (res.code === 1) {
											if (platform == 'H5') {
												const div = document.createElement('divpay')
												div.innerHTML = res.data.pay_data
												document.body.appendChild(div)
											} else {
												this.xunipay(res.data.pay_data)
											}
										}
									})
								}
							}
						})
						// #endif
						// #ifndef MP-WEIXIN

						this.$request('common.pay', {
							order_sn,
							payment,
							platform
						}).then(res => {
							console.log(res)
							if (res.code === 1) {
								if (platform == 'H5') {
									const div = document.createElement('divpay')
									div.innerHTML = res.data.pay_data
									document.body.appendChild(div)
								} else {
									this.pay(res.data.pay_data)
								}
							}
						})
						// #endif
					}
				})
			},
			// 发起 小程序/公众号 支付
			xunipay(pay) {
				var that = this
				// #ifdef MP-WEIXIN
				const SDKVersion = wx.getSystemInfoSync().SDKVersion

				if (this.compareVersion(SDKVersion, '2.19.2') >= 0 || wx.canIUse('requestVirtualPayment')) {
					wx.requestVirtualPayment({
						signData: JSON.stringify({
							offerId: pay.signData.offerId,
							buyQuantity: pay.signData.buyQuantity,
							env: pay.signData.env,
							currencyType: pay.signData.currencyType,
							platform: pay.signData.platform,
							productId: pay.signData.productId,
							goodsPrice: pay.signData.goodsPrice,
							outTradeNo: pay.signData.outTradeNo,
							attach: pay.signData.attach
						}),
						paySig: pay.paySig,
						signature: pay.signature,
						mode: pay.mode,
						success(res) {
							//console.log('requestVirtualPayment success', res)
							uni.showToast({
								title: '支付成功',
								icon: 'none',
								duration: 2000
							})
							that.buttonLoading = true
							that.getUserInfo()
							uni.$emit('updateUserInfo', true)
							uni.hideLoading()
						},
						fail({
							errMsg,
							errCode
						}) {
							//console.error(errMsg, errCode)
							uni.showToast({
								title: '支付失败',
								icon: 'none',
								duration: 2000
							})
							that.buttonLoading = true
							uni.hideLoading()
						}
					})
				} else {
					//console.log('当前用户的客户端版本不支持 wx.requestVirtualPayment')

					uni.showToast({
						title: '当前用户的客户端版本不支持小程序虚拟支付',
						icon: 'none',
						duration: 2000
					})
					this.buttonLoading = true
					uni.hideLoading()
				}
				// #endif

				// // #ifdef H5

				// WeixinJSBridge.invoke(
				// 	'getBrandWCPayRequest', {
				// 		"appId": pay.appId, // 公众号ID，由商户传入
				// 		"timeStamp": pay.timeStamp, // 时间戳，自1970年以来的秒数
				// 		"nonceStr": pay.nonceStr, // 随机串
				// 		"package": pay.package, // 订单详情扩展字符串
				// 		"signType": pay.signType, // 微信签名方式：
				// 		"paySign": pay.paySign // 微信签名
				// 	},
				// 	res => {
				// 		if (res.err_msg == "get_brand_wcpay_request:ok") {
				// 			uni.showToast({
				// 			    title: '支付成功',
				// 				icon: 'none',
				// 				duration: 2000
				// 			});
				// 			this.buttonLoading = true
				// 			this.getUserInfo()
				// 			uni.$emit('updateUserInfo', true)
				// 			uni.hideLoading()
				// 		} else {
				// 			uni.showToast({
				// 			    title: '支付失败',
				// 				icon: 'none',
				// 				duration: 2000
				// 			});
				// 			this.buttonLoading = true
				// 			uni.hideLoading()
				// 		}
				// 	});
				// // #endif

				// // #ifdef APP-PLUS
				// // APP
				// 	uni.getProvider({
				// 		service: "payment",
				// 		success: e => {
				// 			const type = e.provider.includes('wxpay')
				// 			type && uni.requestPayment({
				// 				"provider": "wxpay",
				// 				"orderInfo": pay,
				// 				success: success => {
				// 					uni.showToast({
				// 						title: '支付成功',
				// 						icon: 'none',
				// 						duration: 2000
				// 					});

				// 					this.buttonLoading = true
				// 					this.getUserInfo()
				// 					uni.$emit('updateUserInfo', true)
				// 					uni.hideLoading()
				// 				},
				// 				fail: fail => {
				// 					if(fail.errCode === -8) {
				// 						uni.showToast({
				// 							title: '未安装微信客户端',
				// 							icon: 'none',
				// 							duration: 2000
				// 						});
				// 						this.buttonLoading = true
				// 						uni.hideLoading()
				// 					} else {
				// 						uni.showToast({
				// 							title: '支付失败',
				// 							icon: 'none',
				// 							duration: 2000
				// 						});
				// 						this.buttonLoading = true
				// 						uni.hideLoading()
				// 					}
				// 				}
				// 			})
				// 		},
				// 		fail: e => {
				// 			this.payFail("获取iap支付通道失败")
				// 		}
				// 	});
				// // #endif
			},
			pay(pay) {
				// #ifdef MP-WEIXIN
				uni.requestPayment({
					timeStamp: pay.timeStamp,
					nonceStr: pay.nonceStr,
					package: pay.package,
					signType: pay.signType,
					paySign: pay.paySign,
					success: success => {
						uni.showToast({
							title: '支付成功',
							icon: 'none',
							duration: 2000
						})
						this.buttonLoading = true
						this.getUserInfo()
						uni.$emit('updateUserInfo', true)
						uni.hideLoading()
					},
					fail: fail => {
						uni.showToast({
							title: '支付失败',
							icon: 'none',
							duration: 2000
						})
						this.buttonLoading = true
						uni.hideLoading()
					}
				})
				// #endif

				// #ifdef H5
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						appId: pay.appId, // 公众号ID，由商户传入
						timeStamp: pay.timeStamp, // 时间戳，自1970年以来的秒数
						nonceStr: pay.nonceStr, // 随机串
						package: pay.package, // 订单详情扩展字符串
						signType: pay.signType, // 微信签名方式：
						paySign: pay.paySign // 微信签名
					},
					res => {
						if (res.err_msg == 'get_brand_wcpay_request:ok') {
							uni.showToast({
								title: '支付成功',
								icon: 'none',
								duration: 2000
							})
							this.buttonLoading = true
							this.getUserInfo()
							uni.$emit('updateUserInfo', true)
							uni.hideLoading()
						} else {
							uni.showToast({
								title: '支付失败',
								icon: 'none',
								duration: 2000
							})
							this.buttonLoading = true
							uni.hideLoading()
						}
					}
				)
				// #endif
				// #ifdef APP-PLUS
				// APP
				uni.getProvider({
					service: 'payment',
					success: e => {
						const type = e.provider.includes('wxpay')
						type &&
							uni.requestPayment({
								provider: 'wxpay',
								orderInfo: pay,
								success: success => {
									uni.showToast({
										title: '支付成功',
										icon: 'none',
										duration: 2000
									})

									this.buttonLoading = true
									this.getUserInfo()
									uni.$emit('updateUserInfo', true)
									uni.hideLoading()
								},
								fail: fail => {
									if (fail.errCode === -8) {
										uni.showToast({
											title: '未安装微信客户端',
											icon: 'none',
											duration: 2000
										})
										this.buttonLoading = true
										uni.hideLoading()
									} else {
										uni.showToast({
											title: '支付失败',
											icon: 'none',
											duration: 2000
										})
										this.buttonLoading = true
										uni.hideLoading()
									}
								}
							})
					},
					fail: e => {
						this.payFail('获取iap支付通道失败')
					}
				})
				// #endif
			},
			//判断微信js版本用
			compareVersion(_v1, _v2) {
				if (typeof _v1 !== 'string' || typeof _v2 !== 'string') return 0

				const v1 = _v1.split('.')
				const v2 = _v2.split('.')
				const len = Math.max(v1.length, v2.length)

				while (v1.length < len) {
					v1.push('0')
				}
				while (v2.length < len) {
					v2.push('0')
				}

				for (let i = 0; i < len; i++) {
					const num1 = parseInt(v1[i], 10)
					const num2 = parseInt(v2[i], 10)

					if (num1 > num2) {
						return 1
					} else if (num1 < num2) {
						return -1
					}
				}

				return 0
			}
		}
	}
</script>

<style lang="scss" scoped>
	.VideoPay {
		width: 100%;
		height: 100%;
		position: absolute;
		bottom: -100%;
		left: 0;
		z-index: 100;
		transition: all 0.5s;

		&.active {
			bottom: 0;
		}

		.popup {
			width: 100%;
			min-height: 60%;
			max-height: 60%;
			background: #000;
			border-radius: 20rpx 20rpx 0 0;
			position: absolute;
			bottom: 0;
			left: 0;
			z-index: 1;
			color: #fff;
			padding: 0 40rpx 60rpx 40rpx;
			border-top: 2rpx solid #333;
			display: flex;
			flex-direction: column;

			.p_head {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				position: relative;
				padding: 30rpx 0;
				font-size: 32rpx;

				.left {
					flex: 1;
					display: flex;
					flex-direction: row;

					.text1 {
						font-weight: 700;
						line-height: 48rpx;
					}

					.text2 {
						font-size: 24rpx;
						color: rgba(#fff, 0.5);
						margin: 0 40rpx;
						white-space: nowrap;
						line-height: 48rpx;
					}
				}

				.right {
					color: #ee7f33;
					white-space: nowrap;
					margin-left: 20rpx;
				}
			}

			.p_text {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				font-size: 28rpx;

				.left {
					display: flex;
					flex-direction: row;
					align-items: center;

					.text2 {
						color: #ee7f33;
					}
				}

				.right {
					color: rgba(#fff, 0.7);
				}
			}

			.p_list {
				flex: 1;
				margin-top: 40rpx;
				display: flex;
				flex-wrap: wrap;
				align-content: flex-start;
				overflow-y: scroll;

				.item {
					width: calc((100% - 40rpx) / 2);
					height: 168rpx;
					border-radius: 20rpx;
					background: #fff;
					margin-bottom: 40rpx;
					position: relative;
					overflow: hidden;
					color: #000;
					display: flex;
					flex-direction: column;

					&:nth-child(2n) {
						margin-left: 40rpx;
					}

					&.item2 {
						background: #ee7f33;
						color: #fff;
					}

					.content {
						flex: 1;
						display: flex;
						flex-direction: column;
						justify-content: center;
						// align-items: center;

						.line1 {
							display: flex;
							flex-direction: row;
							align-items: flex-end;
							justify-content: center;

							.text1 {
								font-size: 40rpx;
								font-weight: 700;
							}

							.text2 {
								font-size: 28rpx;
							}
						}

						.line2 {
							font-size: 28rpx;
							display: flex;
							flex-direction: row;
							align-items: center;
							justify-content: center;

							.text2 {
								color: #ee7f33;
							}
						}
					}

					.tips {
						font-size: 28rpx;
						text-align: center;
						background: #ee7f33;
						padding: 8rpx 0;
						color: #fff;
					}

					.badge {
						position: absolute;
						top: -2rpx;
						right: -2rpx;
						padding: 4rpx 16rpx;
						font-size: 24rpx;
						background: #ee7f33;
						border-radius: 0 0 0 20rpx;
						color: #fff;
					}
				}
			}

			.p_info {
				font-size: 24rpx;
				text-align: center;
				margin-top: 20rpx;
			}
		}
	}
</style>